<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use app\common\library\InviteCode;
use OSS\OssClient;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\Exception;
/**
 * 二维码记录管理
 *
 * @icon fa fa-qrcode
 */
class Qrcode extends Backend
{

    /**
     * Qrcode模型对象
     * @var \app\admin\model\Qrcode
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Qrcode;

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        if ($list) {
            foreach ($list as $row) {
                $row->type = \app\admin\model\Type::where('id', $row->origin)->value('name') ?? '';
                //$row->file_path = url($row->file_path);
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $filePath   = '';
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $invite = new InviteCode();
            $params['verify'] = $invite->enCode();
            $params['create_time'] = time();
            $params['update_time'] = time();
            $config = get_addon_config('qrcode');
            $qrcodeParams = $this->request->get();
            $qrcodeParams = array_intersect_key($qrcodeParams, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

            $qrcodeParams['text'] = config('web.site_web_url').'?verify='.$params['verify'];
            //$qrcodeParams['label'] = 'https://www.fastadmin.net'.'?'.$params['verify'];

            $qrCode = \addons\qrcode\library\Service::qrcode($qrcodeParams);
            $saveFilePath = '';
            // 写入到文件
            if ($config['writefile']) {
                $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
                $saveFilePath = '/uploads/qrcode/';
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }
                if (is_really_writable($qrcodePath)) {
                    $filename = md5(implode('', $params)) . '.' . $config['format'];
                    $filePath = $qrcodePath .$filename ;
                    $saveFilePath.= $filename;
                    $qrCode->writeFile($filePath);

                    $ossConfig = get_addon_config('alioss');
                    $oss = new OssClient($ossConfig['accessKeyId'], $ossConfig['accessKeySecret'], $ossConfig['endpoint']);
                    //echo $saveFilePath;exit;
                    try {
                        $ret = $oss->uploadFile($ossConfig['bucket'], ltrim($saveFilePath, "/") , $filePath);
                        //成功不做任何操作
                    } catch (\Exception $e) {
                        $this->error("上传失败(1002)");
                    }
                }
            }
            $params['file_path'] = $saveFilePath;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException()->validate($validate);
                    }
                    $params['update_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

//    public function import()
//    {
//        $file = $this->request->request('file');
//        if (empty($file)) {
//            $this->error(__('No rows were uploaded'));
//        }
//        $imageFilePath = ROOT_PATH . 'public/uploads/qrcode/'; //图片本地存储的路径
//        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
//            mkdir($imageFilePath, 0777, true);
//        }
//        try {
//            $spreadsheet = IOFactory::load(ROOT_PATH.'public'.$file);
//            $worksheet = $spreadsheet->getActiveSheet();
//            $drawings = $worksheet->getDrawingCollection();
//            print_r($drawings);exit;
//            foreach ($drawings as $drawing) {
//                // 获取图片的类型和路径
//                $imageType = $drawing->getDrawingType();
//                $imagePath = $drawing->getPath();
//                // 获取图片的实际文件名
//                $imageName = $drawing->getTitle() . '.' . strtolower(pathinfo($imagePath,PATHINFO_EXTENSION));
//                // 定义保存路径
//                $savePath = $imageFilePath . $imageName; // 确保 'images' 目录存在并可写
//                echo $savePath;
//                file_put_contents($savePath, file_get_contents($imagePath));
//
//                echo "图片已保存： " . $savePath . "\n";
//            }
//        } catch (\Exception $e) {
//            throw $e;
//        }
//    }
}
